package com.lrkj.back.controller;

import cn.com.cbons.mamisay.parent.exception.BusinessException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/upload")
public class UploadController {
	
	
	private String tempPath = "/upload/uploadFiles/"; // 临时文件目录
	private String serverPath = null;
	private int sizeMax = 3;//图片最大上限
    
	private String uploadPicPath = "/upload/pic/"; // 上传文件的目录        图片
	private String uploadVideoPath = "/upload/videos/"; // 上传文件的目录    音频
	private String uploadFilePath = "/upload/files/"; // 上传文件的目录  文件
	/** 统一的编码格式*/
	private static final String encode = "UTF-8";

	@RequestMapping("/greeting")
	public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
		model.addAttribute("name", name);
		return "greeting";
	}
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UploadController.class);
	 
	private PrintWriter encodehead(HttpServletRequest request,HttpServletResponse response) throws IOException, BusinessException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		return response.getWriter();
	} 
	
	@RequestMapping(value = "/filesUploadPics")
	@ResponseBody
	public void filesUploadPics(String lx,String wj, HttpServletRequest request, HttpServletResponse response)  throws BusinessException,ServletException, IOException, Exception{
		PrintWriter out = null;
		int i = Integer.valueOf(lx);
		try {
			out = encodehead(request, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//文件保存目录URL
		String localsaveUrl  = request.getContextPath() + "/upload/";
		String aaa = (String) request.getAttribute("ctx");
//		localsaveUrl = localsaveUrl.
		serverPath = request.getSession().getServletContext().getRealPath("/");
		//定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
		extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,jpg,mp3");
		//最大文件大小
		long maxSize = 999999999;
		response.setContentType("text/html; charset=UTF-8");
		if(!ServletFileUpload.isMultipartContent(request)){
			out.println(getError("请选择文件。"));
			return;
		} 
	
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(5*1024); //最大缓存
		factory.setRepository(new File(serverPath+tempPath));//临时文件目录
		ServletFileUpload upload = new ServletFileUpload(factory); 
		upload.setSizeMax(sizeMax*1024*1024*1024);//文件最大上限
		upload.setHeaderEncoding(encode);
	
		try {
			List<FileItem> items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				if (!item.isFormField()) {
					//检查文件大小
					if(item.getSize() > maxSize){
						out.println(getError("上传文件大小超过限制。"));
						return;
					}
					//检查扩展名
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					if (i == 1) {
						if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
							out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("image") + "格式。"));
							return;
						}
					}
					if (i == 2) {
						if(!Arrays.<String>asList(extMap.get("file").split(",")).contains(fileExt)){
							out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("file") + "格式。"));
							return;
						}
					}
					if (i == 3) {
						if(!Arrays.<String>asList(extMap.get("media").split(",")).contains(fileExt)){
							out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("media") + "格式。"));
							return;
						}
					}
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String pref = df.format(new Date()) + "_" + new Random().nextInt(1000) ;
					String newFileName =pref + "." + fileExt;
					File uploadedFile =  null;
					try{
						if (i == 1) {
							uploadedFile = new File(serverPath, uploadPicPath+newFileName);
						}
						if (i == 2) {
							uploadedFile = new File(serverPath, uploadFilePath+newFileName);
						}
						if (i == 3) {
							uploadedFile = new File(serverPath, uploadVideoPath+newFileName);
						}
						item.write(uploadedFile);
					}catch(Exception e){
						out.println(getError("上传文件失败。"));
						return;
					}

					JSONObject obj = new JSONObject();
					obj.put("error", 1);
					obj.put("wj", wj);
					if (i == 1) {
						obj.put("message", uploadPicPath+newFileName);
						obj.put("sort", 1);
					}
					if (i == 2) {
						obj.put("message", uploadFilePath+newFileName);
						obj.put("sort", 2);
					}
					if (i == 3) {
						obj.put("message", uploadVideoPath+newFileName);
						obj.put("sort", 3);
					}
					out.println(obj.toJSONString());
				}
			}
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private String getError(String message) throws BusinessException {
		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("message", message);
//		obj.put("sort",1);
		return obj.toJSONString();
	}

	@RequestMapping(value = "/uploadfile")
	@ResponseBody
	public String upload( @RequestParam("test") MultipartFile file) {
		if (file.isEmpty()) {
			return "文件为空";
		}
		//上传
		// 获取文件名
		String fileName = file.getOriginalFilename();
		logger.info("上传的文件名为：" + fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		logger.info("上传的后缀名为：" + suffixName);
		// 文件上传后的路径
		String filePath = "D://test//";
		// 解决中文问题，liunx下中文路径，图片显示问题
		// fileName = UUID.randomUUID() + suffixName;
		File dest = new File(filePath + fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest);
			return "上传成功";
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "上传失败";
	}

	//文件下载相关代码
	@RequestMapping("/download")
	public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
		String fileName = "FileUploadTests.java";
		if (fileName != null) {
			//当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
			String realPath = request.getServletContext().getRealPath(
					"//WEB-INF//");
			File file = new File(realPath, fileName);
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition",
						"attachment;fileName=" +  fileName);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("success");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
	//多文件上传
	@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
	@ResponseBody
	public String handleFileUpload(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request)
				.getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					stream = new BufferedOutputStream(new FileOutputStream(
							new File(file.getOriginalFilename())));
					stream.write(bytes);
					stream.close();

				} catch (Exception e) {
					stream = null;
					return "You failed to upload " + i + " => "
							+ e.getMessage();
				}
			} else {
				return "You failed to upload " + i
						+ " because the file was empty.";
			}
		}
		return "upload successful";
	}
}
